LLDB mainline
ClangUtilityFunction.cpp
Go to the documentation of this file.
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
14
15#include <cstdio>
16#include <sys/types.h>
17
18
19#include "lldb/Core/Module.h"
21#include "lldb/Host/Host.h"
23#include "lldb/Target/Target.h"
25#include "lldb/Utility/Log.h"
26#include "lldb/Utility/Stream.h"
27
28using namespace lldb_private;
29
31
33 std::string text, std::string name,
34 bool enable_debugging)
36 exe_scope,
37 std::string(ClangExpressionSourceCode::g_expression_prefix) + text +
38 std::string(ClangExpressionSourceCode::g_expression_suffix),
39 std::move(name), enable_debugging) {
40 // Write the source code to a file so that LLDB's source manager can display
41 // it when debugging the code.
42 if (enable_debugging) {
43 int temp_fd = -1;
44 llvm::SmallString<128> result_path;
45 llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path);
46 if (temp_fd != -1) {
48 text = "#line 1 \"" + std::string(result_path) + "\"\n" + text;
49 size_t bytes_written = text.size();
50 file.Write(text.c_str(), bytes_written);
51 if (bytes_written == text.size()) {
52 // If we successfully wrote the source to a temporary file, replace the
53 // function text with the next text containing the line directive.
57 }
58 file.Close();
59 }
60 }
61}
62
64
65/// Install the utility function into a process
66///
67/// \param[in] diagnostic_manager
68/// A diagnostic manager to report errors and warnings to.
69///
70/// \param[in] exe_ctx
71/// The execution context to install the utility function to.
72///
73/// \return
74/// True on success (no errors); false otherwise.
76 ExecutionContext &exe_ctx) {
78 diagnostic_manager.PutString(eDiagnosticSeverityWarning,
79 "already installed");
80 return false;
81 }
82
83 ////////////////////////////////////
84 // Set up the target and compiler
85 //
86
87 Target *target = exe_ctx.GetTargetPtr();
88
89 if (!target) {
90 diagnostic_manager.PutString(eDiagnosticSeverityError, "invalid target");
91 return false;
92 }
93
94 Process *process = exe_ctx.GetProcessPtr();
95
96 if (!process) {
97 diagnostic_manager.PutString(eDiagnosticSeverityError, "invalid process");
98 return false;
99 }
100
101 // Since we might need to call allocate memory and maybe call code to make
102 // the caller, we need to be stopped.
103 if (process->GetState() != lldb::eStateStopped) {
104 diagnostic_manager.PutString(eDiagnosticSeverityError, "process running");
105 return false;
106 }
107 //////////////////////////
108 // Parse the expression
109 //
110
111 bool keep_result_in_memory = false;
112
113 ResetDeclMap(exe_ctx, keep_result_in_memory);
114
115 if (!DeclMap()->WillParse(exe_ctx, nullptr)) {
116 diagnostic_manager.PutString(
118 "current process state is unsuitable for expression parsing");
119 return false;
120 }
121
122 const bool generate_debug_info = true;
124 generate_debug_info);
125
126 unsigned num_errors = parser.Parse(diagnostic_manager);
127
128 if (num_errors) {
129 ResetDeclMap();
130
131 return false;
132 }
133
134 //////////////////////////////////
135 // JIT the output of the parser
136 //
137
138 bool can_interpret = false; // should stay that way
139
140 Status jit_error = parser.PrepareForExecution(
142 can_interpret, eExecutionPolicyAlways);
143
145 m_jit_process_wp = process->shared_from_this();
146 if (parser.GetGenerateDebugInfo()) {
147 lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule());
148
149 if (jit_module_sp) {
150 ConstString const_func_name(FunctionName());
151 FileSpec jit_file;
152 jit_file.SetFilename(const_func_name);
153 jit_module_sp->SetFileSpecAndObjectName(jit_file, ConstString());
154 m_jit_module_wp = jit_module_sp;
155 target->GetImages().Append(jit_module_sp);
156 }
157 }
158 }
159
160 DeclMap()->DidParse();
161
162 ResetDeclMap();
163
164 if (jit_error.Success()) {
165 return true;
166 } else {
167 const char *error_cstr = jit_error.AsCString();
168 if (error_cstr && error_cstr[0]) {
169 diagnostic_manager.Printf(eDiagnosticSeverityError, "%s", error_cstr);
170 } else {
171 diagnostic_manager.PutString(eDiagnosticSeverityError,
172 "expression can't be interpreted or run");
173 }
174 return false;
175 }
176}
177
179
181 ExecutionContext &exe_ctx, bool keep_result_in_memory) {
182 std::shared_ptr<ClangASTImporter> ast_importer;
183 auto *state = exe_ctx.GetTargetSP()->GetPersistentExpressionStateForLanguage(
185 if (state) {
186 auto *persistent_vars = llvm::cast<ClangPersistentVariables>(state);
187 ast_importer = persistent_vars->GetClangASTImporter();
188 }
189 m_expr_decl_map_up = std::make_unique<ClangExpressionDeclMap>(
190 keep_result_in_memory, nullptr, exe_ctx.GetTargetSP(), ast_importer,
191 nullptr);
192}
void DidParse()
Disable the state needed for parsing and IR transformation.
"lldb/Expression/ClangExpressionParser.h" Encapsulates an instance of Clang that can parse expression...
Status PrepareForExecution(lldb::addr_t &func_addr, lldb::addr_t &func_end, lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx, bool &can_interpret, lldb_private::ExecutionPolicy execution_policy) override
Ready an already-parsed expression for execution, possibly evaluating it statically.
unsigned Parse(DiagnosticManager &diagnostic_manager)
Parse a single expression and convert it to IR using Clang.
std::unique_ptr< ClangExpressionDeclMap > m_expr_decl_map_up
ClangExpressionDeclMap * DeclMap()
ClangUtilityFunction(ExecutionContextScope &exe_scope, std::string text, std::string name, bool enable_debugging)
Constructor.
bool Install(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx) override
Install the utility function into a process.
A uniqued constant string class.
Definition: ConstString.h:40
size_t Printf(DiagnosticSeverity severity, const char *format,...) __attribute__((format(printf
size_t void PutString(DiagnosticSeverity severity, llvm::StringRef str)
"lldb/Target/ExecutionContextScope.h" Inherit from this if your object can reconstruct its execution ...
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
ExecutionContextScope * GetBestExecutionContextScope() const
const lldb::TargetSP & GetTargetSP() const
Get accessor to get the target shared pointer.
Target * GetTargetPtr() const
Returns a pointer to the target object.
Process * GetProcessPtr() const
Returns a pointer to the process object.
lldb::addr_t m_jit_end_addr
The address of the JITted function within the JIT allocation.
Definition: Expression.h:97
lldb::ProcessWP m_jit_process_wp
Expression's always have to have a target...
Definition: Expression.h:91
lldb::addr_t m_jit_start_addr
An expression might have a process, but it doesn't need to (e.g.
Definition: Expression.h:94
A file utility class.
Definition: FileSpec.h:56
void SetFilename(ConstString filename)
Filename string set accessor.
Definition: FileSpec.cpp:345
@ eOpenOptionWriteOnly
Definition: File.h:52
void Append(const lldb::ModuleSP &module_sp, bool notify=true)
Append a module to the module list.
Definition: ModuleList.cpp:247
Status Close() override
Flush any buffers and release any resources owned by the file.
Definition: File.cpp:315
Status Write(const void *buf, size_t &num_bytes) override
Write bytes from buf to a file at the current file position.
Definition: File.cpp:582
A plug-in interface definition class for debugging a process.
Definition: Process.h:341
lldb::StateType GetState()
Get accessor for the current process state.
Definition: Process.cpp:1301
An error handling class.
Definition: Status.h:44
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition: Status.cpp:130
bool Success() const
Test for success condition.
Definition: Status.cpp:279
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition: Target.h:972
"lldb/Expression/UtilityFunction.h" Encapsulates a bit of source code that provides a function that i...
const char * FunctionName() override
Return the function name that should be used for executing the expression.
std::shared_ptr< IRExecutionUnit > m_execution_unit_sp
std::string m_function_text
The text of the function. Must be a well-formed translation unit.
#define LLDB_INVALID_ADDRESS
Definition: lldb-defines.h:82
A class that represents a running process on the host machine.
Definition: SBAttachInfo.h:14
@ eStateStopped
Process or thread is stopped and can be examined.
@ eLanguageTypeC
Non-standardized C, such as K&R.
std::shared_ptr< lldb_private::Module > ModuleSP
Definition: lldb-forward.h:365