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 
9 #include "ClangExpressionSourceCode.h"
10 
11 #include "clang/Basic/CharInfo.h"
12 #include "clang/Basic/FileManager.h"
13 #include "clang/Basic/SourceManager.h"
14 #include "clang/Lex/Lexer.h"
15 #include "llvm/ADT/StringRef.h"
16 
17 #include "Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h"
18 #include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h"
19 #include "lldb/Symbol/Block.h"
20 #include "lldb/Symbol/CompileUnit.h"
21 #include "lldb/Symbol/DebugMacros.h"
22 #include "lldb/Symbol/TypeSystem.h"
23 #include "lldb/Symbol/VariableList.h"
24 #include "lldb/Target/ExecutionContext.h"
25 #include "lldb/Target/Language.h"
26 #include "lldb/Target/Platform.h"
27 #include "lldb/Target/StackFrame.h"
28 #include "lldb/Target/Target.h"
29 #include "lldb/Utility/StreamString.h"
30 
31 using namespace lldb_private;
32 
33 #define PREFIX_NAME "<lldb wrapper prefix>"
34 
35 const llvm::StringRef ClangExpressionSourceCode::g_prefix_file_name = PREFIX_NAME;
36 
37 const char *ClangExpressionSourceCode::g_expression_prefix =
38 "#line 1 \"" PREFIX_NAME R"("
39 #ifndef offsetof
40 #define offsetof(t, d) __builtin_offsetof(t, d)
41 #endif
42 #ifndef NULL
43 #define NULL (__null)
44 #endif
45 #ifndef Nil
46 #define Nil (__null)
47 #endif
48 #ifndef nil
49 #define nil (__null)
50 #endif
51 #ifndef YES
52 #define YES ((BOOL)1)
53 #endif
54 #ifndef NO
55 #define NO ((BOOL)0)
56 #endif
57 typedef __INT8_TYPE__ int8_t;
58 typedef __UINT8_TYPE__ uint8_t;
59 typedef __INT16_TYPE__ int16_t;
60 typedef __UINT16_TYPE__ uint16_t;
61 typedef __INT32_TYPE__ int32_t;
62 typedef __UINT32_TYPE__ uint32_t;
63 typedef __INT64_TYPE__ int64_t;
64 typedef __UINT64_TYPE__ uint64_t;
65 typedef __INTPTR_TYPE__ intptr_t;
66 typedef __UINTPTR_TYPE__ uintptr_t;
67 typedef __SIZE_TYPE__ size_t;
68 typedef __PTRDIFF_TYPE__ ptrdiff_t;
69 typedef unsigned short unichar;
70 extern "C"
71 {
72     int printf(const char * __restrict, ...);
73 }
74 )";
75 
76 namespace {
77 
78 class AddMacroState {
79   enum State {
80     CURRENT_FILE_NOT_YET_PUSHED,
81     CURRENT_FILE_PUSHED,
82     CURRENT_FILE_POPPED
83   };
84 
85 public:
86   AddMacroState(const FileSpec &current_file, const uint32_t current_file_line)
87       : m_state(CURRENT_FILE_NOT_YET_PUSHED), m_current_file(current_file),
88         m_current_file_line(current_file_line) {}
89 
90   void StartFile(const FileSpec &file) {
91     m_file_stack.push_back(file);
92     if (file == m_current_file)
93       m_state = CURRENT_FILE_PUSHED;
94   }
95 
96   void EndFile() {
97     if (m_file_stack.size() == 0)
98       return;
99 
100     FileSpec old_top = m_file_stack.back();
101     m_file_stack.pop_back();
102     if (old_top == m_current_file)
103       m_state = CURRENT_FILE_POPPED;
104   }
105 
106   // An entry is valid if it occurs before the current line in the current
107   // file.
108   bool IsValidEntry(uint32_t line) {
109     switch (m_state) {
110     case CURRENT_FILE_NOT_YET_PUSHED:
111       return true;
112     case CURRENT_FILE_PUSHED:
113       // If we are in file included in the current file, the entry should be
114       // added.
115       if (m_file_stack.back() != m_current_file)
116         return true;
117 
118       return line < m_current_file_line;
119     default:
120       return false;
121     }
122   }
123 
124 private:
125   std::vector<FileSpec> m_file_stack;
126   State m_state;
127   FileSpec m_current_file;
128   uint32_t m_current_file_line;
129 };
130 
131 } // anonymous namespace
132 
133 static void AddMacros(const DebugMacros *dm, CompileUnit *comp_unit,
134                       AddMacroState &state, StreamString &stream) {
135   if (dm == nullptr)
136     return;
137 
138   for (size_t i = 0; i < dm->GetNumMacroEntries(); i++) {
139     const DebugMacroEntry &entry = dm->GetMacroEntryAtIndex(i);
140     uint32_t line;
141 
142     switch (entry.GetType()) {
143     case DebugMacroEntry::DEFINE:
144       if (state.IsValidEntry(entry.GetLineNumber()))
145         stream.Printf("#define %s\n", entry.GetMacroString().AsCString());
146       else
147         return;
148       break;
149     case DebugMacroEntry::UNDEF:
150       if (state.IsValidEntry(entry.GetLineNumber()))
151         stream.Printf("#undef %s\n", entry.GetMacroString().AsCString());
152       else
153         return;
154       break;
155     case DebugMacroEntry::START_FILE:
156       line = entry.GetLineNumber();
157       if (state.IsValidEntry(line))
158         state.StartFile(entry.GetFileSpec(comp_unit));
159       else
160         return;
161       break;
162     case DebugMacroEntry::END_FILE:
163       state.EndFile();
164       break;
165     case DebugMacroEntry::INDIRECT:
166       AddMacros(entry.GetIndirectDebugMacros(), comp_unit, state, stream);
167       break;
168     default:
169       // This is an unknown/invalid entry. Ignore.
170       break;
171     }
172   }
173 }
174 
175 lldb_private::ClangExpressionSourceCode::ClangExpressionSourceCode(
176     llvm::StringRef filename, llvm::StringRef name, llvm::StringRef prefix,
177     llvm::StringRef body, Wrapping wrap, WrapKind wrap_kind)
178     : ExpressionSourceCode(name, prefix, body, wrap), m_wrap_kind(wrap_kind) {
179   // Use #line markers to pretend that we have a single-line source file
180   // containing only the user expression. This will hide our wrapper code
181   // from the user when we render diagnostics with Clang.
182   m_start_marker = "#line 1 \"" + filename.str() + "\"\n";
183   m_end_marker = "\n;\n#line 1 \"<lldb wrapper suffix>\"\n";
184 }
185 
186 namespace {
187 /// Allows checking if a token is contained in a given expression.
188 class TokenVerifier {
189   /// The tokens we found in the expression.
190   llvm::StringSet<> m_tokens;
191 
192 public:
193   TokenVerifier(std::string body);
194   /// Returns true iff the given expression body contained a token with the
195   /// given content.
196   bool hasToken(llvm::StringRef token) const {
197     return m_tokens.find(token) != m_tokens.end();
198   }
199 };
200 } // namespace
201 
202 TokenVerifier::TokenVerifier(std::string body) {
203   using namespace clang;
204 
205   // We only care about tokens and not their original source locations. If we
206   // move the whole expression to only be in one line we can simplify the
207   // following code that extracts the token contents.
208   std::replace(body.begin(), body.end(), '\n', ' ');
209   std::replace(body.begin(), body.end(), '\r', ' ');
210 
211   FileSystemOptions file_opts;
212   FileManager file_mgr(file_opts,
213                        FileSystem::Instance().GetVirtualFileSystem());
214 
215   // Let's build the actual source code Clang needs and setup some utility
216   // objects.
217   llvm::IntrusiveRefCntPtr<DiagnosticIDs> diag_ids(new DiagnosticIDs());
218   llvm::IntrusiveRefCntPtr<DiagnosticOptions> diags_opts(
219       new DiagnosticOptions());
220   DiagnosticsEngine diags(diag_ids, diags_opts);
221   clang::SourceManager SM(diags, file_mgr);
222   auto buf = llvm::MemoryBuffer::getMemBuffer(body);
223 
224   FileID FID = SM.createFileID(clang::SourceManager::Unowned, buf.get());
225 
226   // Let's just enable the latest ObjC and C++ which should get most tokens
227   // right.
228   LangOptions Opts;
229   Opts.ObjC = true;
230   Opts.DollarIdents = true;
231   Opts.CPlusPlus17 = true;
232   Opts.LineComment = true;
233 
234   Lexer lex(FID, buf.get(), SM, Opts);
235 
236   Token token;
237   bool exit = false;
238   while (!exit) {
239     // Returns true if this is the last token we get from the lexer.
240     exit = lex.LexFromRawLexer(token);
241 
242     // Extract the column number which we need to extract the token content.
243     // Our expression is just one line, so we don't need to handle any line
244     // numbers here.
245     bool invalid = false;
246     unsigned start = SM.getSpellingColumnNumber(token.getLocation(), &invalid);
247     if (invalid)
248       continue;
249     // Column numbers start at 1, but indexes in our string start at 0.
250     --start;
251 
252     // Annotations don't have a length, so let's skip them.
253     if (token.isAnnotation())
254       continue;
255 
256     // Extract the token string from our source code and store it.
257     std::string token_str = body.substr(start, token.getLength());
258     if (token_str.empty())
259       continue;
260     m_tokens.insert(token_str);
261   }
262 }
263 
264 void ClangExpressionSourceCode::AddLocalVariableDecls(
265     const lldb::VariableListSP &var_list_sp, StreamString &stream,
266     const std::string &expr) const {
267   TokenVerifier tokens(expr);
268 
269   for (size_t i = 0; i < var_list_sp->GetSize(); i++) {
270     lldb::VariableSP var_sp = var_list_sp->GetVariableAtIndex(i);
271 
272     ConstString var_name = var_sp->GetName();
273 
274 
275     // We can check for .block_descriptor w/o checking for langauge since this
276     // is not a valid identifier in either C or C++.
277     if (!var_name || var_name == ".block_descriptor")
278       continue;
279 
280     if (!expr.empty() && !tokens.hasToken(var_name.GetStringRef()))
281       continue;
282 
283     const bool is_objc = m_wrap_kind == WrapKind::ObjCInstanceMethod ||
284                          m_wrap_kind == WrapKind::ObjCStaticMethod;
285     if ((var_name == "self" || var_name == "_cmd") && is_objc)
286       continue;
287 
288     if (var_name == "this" && m_wrap_kind == WrapKind::CppMemberFunction)
289       continue;
290 
291     stream.Printf("using $__lldb_local_vars::%s;\n", var_name.AsCString());
292   }
293 }
294 
295 bool ClangExpressionSourceCode::GetText(
296     std::string &text, ExecutionContext &exe_ctx, bool add_locals,
297     bool force_add_all_locals, llvm::ArrayRef<std::string> modules) const {
298   const char *target_specific_defines = "typedef signed char BOOL;\n";
299   std::string module_macros;
300 
301   Target *target = exe_ctx.GetTargetPtr();
302   if (target) {
303     if (target->GetArchitecture().GetMachine() == llvm::Triple::aarch64 ||
304         target->GetArchitecture().GetMachine() == llvm::Triple::aarch64_32) {
305       target_specific_defines = "typedef bool BOOL;\n";
306     }
307     if (target->GetArchitecture().GetMachine() == llvm::Triple::x86_64) {
308       if (lldb::PlatformSP platform_sp = target->GetPlatform()) {
309         static ConstString g_platform_ios_simulator("ios-simulator");
310         if (platform_sp->GetPluginName() == g_platform_ios_simulator) {
311           target_specific_defines = "typedef bool BOOL;\n";
312         }
313       }
314     }
315 
316     ClangModulesDeclVendor *decl_vendor = target->GetClangModulesDeclVendor();
317     auto *persistent_vars = llvm::cast<ClangPersistentVariables>(
318         target->GetPersistentExpressionStateForLanguage(lldb::eLanguageTypeC));
319     if (decl_vendor && persistent_vars) {
320       const ClangModulesDeclVendor::ModuleVector &hand_imported_modules =
321           persistent_vars->GetHandLoadedClangModules();
322       ClangModulesDeclVendor::ModuleVector modules_for_macros;
323 
324       for (ClangModulesDeclVendor::ModuleID module : hand_imported_modules) {
325         modules_for_macros.push_back(module);
326       }
327 
328       if (target->GetEnableAutoImportClangModules()) {
329         if (StackFrame *frame = exe_ctx.GetFramePtr()) {
330           if (Block *block = frame->GetFrameBlock()) {
331             SymbolContext sc;
332 
333             block->CalculateSymbolContext(&sc);
334 
335             if (sc.comp_unit) {
336               StreamString error_stream;
337 
338               decl_vendor->AddModulesForCompileUnit(
339                   *sc.comp_unit, modules_for_macros, error_stream);
340             }
341           }
342         }
343       }
344 
345       decl_vendor->ForEachMacro(
346           modules_for_macros,
347           [&module_macros](const std::string &expansion) -> bool {
348             module_macros.append(expansion);
349             module_macros.append("\n");
350             return false;
351           });
352     }
353   }
354 
355   StreamString debug_macros_stream;
356   StreamString lldb_local_var_decls;
357   if (StackFrame *frame = exe_ctx.GetFramePtr()) {
358     const SymbolContext &sc = frame->GetSymbolContext(
359         lldb::eSymbolContextCompUnit | lldb::eSymbolContextLineEntry);
360 
361     if (sc.comp_unit && sc.line_entry.IsValid()) {
362       DebugMacros *dm = sc.comp_unit->GetDebugMacros();
363       if (dm) {
364         AddMacroState state(sc.line_entry.file, sc.line_entry.line);
365         AddMacros(dm, sc.comp_unit, state, debug_macros_stream);
366       }
367     }
368 
369     if (add_locals)
370       if (target->GetInjectLocalVariables(&exe_ctx)) {
371         lldb::VariableListSP var_list_sp =
372             frame->GetInScopeVariableList(false, true);
373         AddLocalVariableDecls(var_list_sp, lldb_local_var_decls,
374                               force_add_all_locals ? "" : m_body);
375       }
376   }
377 
378   if (m_wrap) {
379     // Generate a list of @import statements that will import the specified
380     // module into our expression.
381     std::string module_imports;
382     for (const std::string &module : modules) {
383       module_imports.append("@import ");
384       module_imports.append(module);
385       module_imports.append(";\n");
386     }
387 
388     StreamString wrap_stream;
389 
390     wrap_stream.Printf("%s\n%s\n%s\n%s\n%s\n", module_macros.c_str(),
391                        debug_macros_stream.GetData(), g_expression_prefix,
392                        target_specific_defines, m_prefix.c_str());
393 
394     // First construct a tagged form of the user expression so we can find it
395     // later:
396     std::string tagged_body;
397     tagged_body.append(m_start_marker);
398     tagged_body.append(m_body);
399     tagged_body.append(m_end_marker);
400 
401     switch (m_wrap_kind) {
402     case WrapKind::Function:
403       wrap_stream.Printf("%s"
404                          "void                           \n"
405                          "%s(void *$__lldb_arg)          \n"
406                          "{                              \n"
407                          "    %s;                        \n"
408                          "%s"
409                          "}                              \n",
410                          module_imports.c_str(), m_name.c_str(),
411                          lldb_local_var_decls.GetData(), tagged_body.c_str());
412       break;
413     case WrapKind::CppMemberFunction:
414       wrap_stream.Printf("%s"
415                          "void                                   \n"
416                          "$__lldb_class::%s(void *$__lldb_arg)   \n"
417                          "{                                      \n"
418                          "    %s;                                \n"
419                          "%s"
420                          "}                                      \n",
421                          module_imports.c_str(), m_name.c_str(),
422                          lldb_local_var_decls.GetData(), tagged_body.c_str());
423       break;
424     case WrapKind::ObjCInstanceMethod:
425       wrap_stream.Printf(
426           "%s"
427           "@interface $__lldb_objc_class ($__lldb_category)       \n"
428           "-(void)%s:(void *)$__lldb_arg;                         \n"
429           "@end                                                   \n"
430           "@implementation $__lldb_objc_class ($__lldb_category)  \n"
431           "-(void)%s:(void *)$__lldb_arg                          \n"
432           "{                                                      \n"
433           "    %s;                                                \n"
434           "%s"
435           "}                                                      \n"
436           "@end                                                   \n",
437           module_imports.c_str(), m_name.c_str(), m_name.c_str(),
438           lldb_local_var_decls.GetData(), tagged_body.c_str());
439       break;
440 
441     case WrapKind::ObjCStaticMethod:
442       wrap_stream.Printf(
443           "%s"
444           "@interface $__lldb_objc_class ($__lldb_category)        \n"
445           "+(void)%s:(void *)$__lldb_arg;                          \n"
446           "@end                                                    \n"
447           "@implementation $__lldb_objc_class ($__lldb_category)   \n"
448           "+(void)%s:(void *)$__lldb_arg                           \n"
449           "{                                                       \n"
450           "    %s;                                                 \n"
451           "%s"
452           "}                                                       \n"
453           "@end                                                    \n",
454           module_imports.c_str(), m_name.c_str(), m_name.c_str(),
455           lldb_local_var_decls.GetData(), tagged_body.c_str());
456       break;
457     }
458 
459     text = std::string(wrap_stream.GetString());
460   } else {
461     text.append(m_body);
462   }
463 
464   return true;
465 }
466 
467 bool ClangExpressionSourceCode::GetOriginalBodyBounds(
468     std::string transformed_text, size_t &start_loc, size_t &end_loc) {
469   start_loc = transformed_text.find(m_start_marker);
470   if (start_loc == std::string::npos)
471     return false;
472   start_loc += m_start_marker.size();
473   end_loc = transformed_text.find(m_end_marker);
474   return end_loc != std::string::npos;
475 }
476