1 //===-- ClangUtilityFunction.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 "lldb/Host/Config.h"
10 
11 #include "ClangUtilityFunction.h"
12 #include "ClangExpressionDeclMap.h"
13 #include "ClangExpressionParser.h"
14 #include "ClangExpressionSourceCode.h"
15 #include "ClangPersistentVariables.h"
16 
17 #include <stdio.h>
18 #if HAVE_SYS_TYPES_H
19 #include <sys/types.h>
20 #endif
21 
22 
23 #include "lldb/Core/Module.h"
24 #include "lldb/Core/StreamFile.h"
25 #include "lldb/Expression/IRExecutionUnit.h"
26 #include "lldb/Host/Host.h"
27 #include "lldb/Target/ExecutionContext.h"
28 #include "lldb/Target/Target.h"
29 #include "lldb/Utility/ConstString.h"
30 #include "lldb/Utility/Log.h"
31 #include "lldb/Utility/Stream.h"
32 
33 using namespace lldb_private;
34 
35 char ClangUtilityFunction::ID;
36 
37 /// Constructor
38 ///
39 /// \param[in] text
40 ///     The text of the function.  Must be a full translation unit.
41 ///
42 /// \param[in] name
43 ///     The name of the function, as used in the text.
44 ClangUtilityFunction::ClangUtilityFunction(ExecutionContextScope &exe_scope,
45                                            std::string text, std::string name)
46     : UtilityFunction(exe_scope, std::move(text), std::move(name)) {
47   m_function_text.assign(ClangExpressionSourceCode::g_expression_prefix);
48 }
49 
50 ClangUtilityFunction::~ClangUtilityFunction() {}
51 
52 /// Install the utility function into a process
53 ///
54 /// \param[in] diagnostic_manager
55 ///     A diagnostic manager to report errors and warnings to.
56 ///
57 /// \param[in] exe_ctx
58 ///     The execution context to install the utility function to.
59 ///
60 /// \return
61 ///     True on success (no errors); false otherwise.
62 bool ClangUtilityFunction::Install(DiagnosticManager &diagnostic_manager,
63                                    ExecutionContext &exe_ctx) {
64   if (m_jit_start_addr != LLDB_INVALID_ADDRESS) {
65     diagnostic_manager.PutString(eDiagnosticSeverityWarning,
66                                  "already installed");
67     return false;
68   }
69 
70   ////////////////////////////////////
71   // Set up the target and compiler
72   //
73 
74   Target *target = exe_ctx.GetTargetPtr();
75 
76   if (!target) {
77     diagnostic_manager.PutString(eDiagnosticSeverityError, "invalid target");
78     return false;
79   }
80 
81   Process *process = exe_ctx.GetProcessPtr();
82 
83   if (!process) {
84     diagnostic_manager.PutString(eDiagnosticSeverityError, "invalid process");
85     return false;
86   }
87 
88   //////////////////////////
89   // Parse the expression
90   //
91 
92   bool keep_result_in_memory = false;
93 
94   ResetDeclMap(exe_ctx, keep_result_in_memory);
95 
96   if (!DeclMap()->WillParse(exe_ctx, nullptr)) {
97     diagnostic_manager.PutString(
98         eDiagnosticSeverityError,
99         "current process state is unsuitable for expression parsing");
100     return false;
101   }
102 
103   const bool generate_debug_info = true;
104   ClangExpressionParser parser(exe_ctx.GetBestExecutionContextScope(), *this,
105                                generate_debug_info);
106 
107   unsigned num_errors = parser.Parse(diagnostic_manager);
108 
109   if (num_errors) {
110     ResetDeclMap();
111 
112     return false;
113   }
114 
115   //////////////////////////////////
116   // JIT the output of the parser
117   //
118 
119   bool can_interpret = false; // should stay that way
120 
121   Status jit_error = parser.PrepareForExecution(
122       m_jit_start_addr, m_jit_end_addr, m_execution_unit_sp, exe_ctx,
123       can_interpret, eExecutionPolicyAlways);
124 
125   if (m_jit_start_addr != LLDB_INVALID_ADDRESS) {
126     m_jit_process_wp = process->shared_from_this();
127     if (parser.GetGenerateDebugInfo()) {
128       lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule());
129 
130       if (jit_module_sp) {
131         ConstString const_func_name(FunctionName());
132         FileSpec jit_file;
133         jit_file.GetFilename() = const_func_name;
134         jit_module_sp->SetFileSpecAndObjectName(jit_file, ConstString());
135         m_jit_module_wp = jit_module_sp;
136         target->GetImages().Append(jit_module_sp);
137       }
138     }
139   }
140 
141   DeclMap()->DidParse();
142 
143   ResetDeclMap();
144 
145   if (jit_error.Success()) {
146     return true;
147   } else {
148     const char *error_cstr = jit_error.AsCString();
149     if (error_cstr && error_cstr[0]) {
150       diagnostic_manager.Printf(eDiagnosticSeverityError, "%s", error_cstr);
151     } else {
152       diagnostic_manager.PutString(eDiagnosticSeverityError,
153                                    "expression can't be interpreted or run");
154     }
155     return false;
156   }
157 }
158 
159 void ClangUtilityFunction::ClangUtilityFunctionHelper::ResetDeclMap(
160     ExecutionContext &exe_ctx, bool keep_result_in_memory) {
161   std::shared_ptr<ClangASTImporter> ast_importer;
162   auto *state = exe_ctx.GetTargetSP()->GetPersistentExpressionStateForLanguage(
163       lldb::eLanguageTypeC);
164   if (state) {
165     auto *persistent_vars = llvm::cast<ClangPersistentVariables>(state);
166     ast_importer = persistent_vars->GetClangASTImporter();
167   }
168   m_expr_decl_map_up = std::make_unique<ClangExpressionDeclMap>(
169       keep_result_in_memory, nullptr, exe_ctx.GetTargetSP(), ast_importer,
170       nullptr);
171 }
172