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 
9 #include "lldb/Host/Config.h"
10 
11 #include "ClangUtilityFunction.h"
12 #include "ClangExpressionDeclMap.h"
13 #include "ClangExpressionParser.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"
26 #include "lldb/Host/Host.h"
28 #include "lldb/Target/Target.h"
30 #include "lldb/Utility/Log.h"
31 #include "lldb/Utility/Stream.h"
32 
33 using namespace lldb_private;
34 
36 
38  std::string text, std::string name,
39  bool enable_debugging)
41  exe_scope,
42  std::string(ClangExpressionSourceCode::g_expression_prefix) + text +
43  std::string(ClangExpressionSourceCode::g_expression_suffix),
44  std::move(name), enable_debugging) {
45  // Write the source code to a file so that LLDB's source manager can display
46  // it when debugging the code.
47  if (enable_debugging) {
48  int temp_fd = -1;
49  llvm::SmallString<128> result_path;
50  llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path);
51  if (temp_fd != -1) {
53  text = "#line 1 \"" + std::string(result_path) + "\"\n" + text;
54  size_t bytes_written = text.size();
55  file.Write(text.c_str(), bytes_written);
56  if (bytes_written == text.size()) {
57  // If we successfully wrote the source to a temporary file, replace the
58  // function text with the next text containing the line directive.
62  }
63  file.Close();
64  }
65  }
66 }
67 
69 
70 /// Install the utility function into a process
71 ///
72 /// \param[in] diagnostic_manager
73 /// A diagnostic manager to report errors and warnings to.
74 ///
75 /// \param[in] exe_ctx
76 /// The execution context to install the utility function to.
77 ///
78 /// \return
79 /// True on success (no errors); false otherwise.
81  ExecutionContext &exe_ctx) {
83  diagnostic_manager.PutString(eDiagnosticSeverityWarning,
84  "already installed");
85  return false;
86  }
87 
88  ////////////////////////////////////
89  // Set up the target and compiler
90  //
91 
92  Target *target = exe_ctx.GetTargetPtr();
93 
94  if (!target) {
95  diagnostic_manager.PutString(eDiagnosticSeverityError, "invalid target");
96  return false;
97  }
98 
99  Process *process = exe_ctx.GetProcessPtr();
100 
101  if (!process) {
102  diagnostic_manager.PutString(eDiagnosticSeverityError, "invalid process");
103  return false;
104  }
105 
106  //////////////////////////
107  // Parse the expression
108  //
109 
110  bool keep_result_in_memory = false;
111 
112  ResetDeclMap(exe_ctx, keep_result_in_memory);
113 
114  if (!DeclMap()->WillParse(exe_ctx, nullptr)) {
115  diagnostic_manager.PutString(
117  "current process state is unsuitable for expression parsing");
118  return false;
119  }
120 
121  const bool generate_debug_info = true;
122  ClangExpressionParser parser(exe_ctx.GetBestExecutionContextScope(), *this,
123  generate_debug_info);
124 
125  unsigned num_errors = parser.Parse(diagnostic_manager);
126 
127  if (num_errors) {
128  ResetDeclMap();
129 
130  return false;
131  }
132 
133  //////////////////////////////////
134  // JIT the output of the parser
135  //
136 
137  bool can_interpret = false; // should stay that way
138 
139  Status jit_error = parser.PrepareForExecution(
141  can_interpret, eExecutionPolicyAlways);
142 
144  m_jit_process_wp = process->shared_from_this();
145  if (parser.GetGenerateDebugInfo()) {
146  lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule());
147 
148  if (jit_module_sp) {
149  ConstString const_func_name(FunctionName());
150  FileSpec jit_file;
151  jit_file.GetFilename() = const_func_name;
152  jit_module_sp->SetFileSpecAndObjectName(jit_file, ConstString());
153  m_jit_module_wp = jit_module_sp;
154  target->GetImages().Append(jit_module_sp);
155  }
156  }
157  }
158 
159  DeclMap()->DidParse();
160 
161  ResetDeclMap();
162 
163  if (jit_error.Success()) {
164  return true;
165  } else {
166  const char *error_cstr = jit_error.AsCString();
167  if (error_cstr && error_cstr[0]) {
168  diagnostic_manager.Printf(eDiagnosticSeverityError, "%s", error_cstr);
169  } else {
170  diagnostic_manager.PutString(eDiagnosticSeverityError,
171  "expression can't be interpreted or run");
172  }
173  return false;
174  }
175 }
176 
178  ExecutionContext &exe_ctx, bool keep_result_in_memory) {
179  std::shared_ptr<ClangASTImporter> ast_importer;
180  auto *state = exe_ctx.GetTargetSP()->GetPersistentExpressionStateForLanguage(
182  if (state) {
183  auto *persistent_vars = llvm::cast<ClangPersistentVariables>(state);
184  ast_importer = persistent_vars->GetClangASTImporter();
185  }
186  m_expr_decl_map_up = std::make_unique<ClangExpressionDeclMap>(
187  keep_result_in_memory, nullptr, exe_ctx.GetTargetSP(), ast_importer,
188  nullptr);
189 }
lldb_private::ExecutionContext
Definition: ExecutionContext.h:291
ClangExpressionSourceCode.h
lldb_private::UtilityFunction::m_jit_module_wp
lldb::ModuleWP m_jit_module_wp
Definition: UtilityFunction.h:115
lldb_private::ExecutionContext::GetProcessPtr
Process * GetProcessPtr() const
Returns a pointer to the process object.
Definition: ExecutionContext.cpp:208
Host.h
lldb_private::ClangExpressionSourceCode::g_expression_suffix
static const char * g_expression_suffix
Definition: ClangExpressionSourceCode.h:30
lldb_private::Expression::m_jit_process_wp
lldb::ProcessWP m_jit_process_wp
Expression's always have to have a target...
Definition: Expression.h:93
lldb_private::Process
Definition: Process.h:343
lldb_private::ClangUtilityFunction::ClangUtilityFunction
ClangUtilityFunction(ExecutionContextScope &exe_scope, std::string text, std::string name, bool enable_debugging)
Constructor.
Definition: ClangUtilityFunction.cpp:37
Module.h
lldb_private::ClangExpressionSourceCode::g_expression_prefix
static const char * g_expression_prefix
Definition: ClangExpressionSourceCode.h:29
lldb_private::Expression::m_jit_start_addr
lldb::addr_t m_jit_start_addr
An expression might have a process, but it doesn't need to (e.g.
Definition: Expression.h:96
ClangUtilityFunction.h
lldb_private::eExecutionPolicyAlways
@ eExecutionPolicyAlways
Definition: lldb-private-enumerations.h:147
lldb_private::Target
Definition: Target.h:447
lldb_private::eDiagnosticSeverityWarning
@ eDiagnosticSeverityWarning
Definition: DiagnosticManager.h:33
lldb_private::Target::GetImages
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition: Target.h:921
lldb_private::NativeFile::Close
Status Close() override
Flush any buffers and release any resources owned by the file.
Definition: File.cpp:307
Target.h
lldb_private::FileSpec
Definition: FileSpec.h:56
lldb_private::Status::Success
bool Success() const
Test for success condition.
Definition: Status.cpp:288
lldb_private::eDiagnosticSeverityError
@ eDiagnosticSeverityError
Definition: DiagnosticManager.h:32
lldb_private::ExpressionParser::GetGenerateDebugInfo
bool GetGenerateDebugInfo() const
Definition: ExpressionParser.h:128
Log.h
lldb_private::ExecutionContextScope
Definition: ExecutionContextScope.h:32
lldb_private::ClangExpressionParser::PrepareForExecution
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.
Definition: ClangExpressionParser.cpp:1320
lldb_private::Expression::m_jit_end_addr
lldb::addr_t m_jit_end_addr
The address of the JITted function within the JIT allocation.
Definition: Expression.h:99
ClangPersistentVariables.h
lldb_private::ClangExpressionParser::Parse
unsigned Parse(DiagnosticManager &diagnostic_manager)
Parse a single expression and convert it to IR using Clang.
Definition: ClangExpressionParser.cpp:1029
lldb_private::ConstString
Definition: ConstString.h:40
lldb_private::ClangUtilityFunction::~ClangUtilityFunction
~ClangUtilityFunction() override
Definition: ClangUtilityFunction.cpp:68
lldb_private::UtilityFunction::m_execution_unit_sp
std::shared_ptr< IRExecutionUnit > m_execution_unit_sp
Definition: UtilityFunction.h:114
IRExecutionUnit.h
string
string(SUBSTRING ${p} 10 -1 pStripped) if($
Definition: Plugins/CMakeLists.txt:38
ClangExpressionParser.h
lldb_private::ClangUtilityFunction::ClangUtilityFunctionHelper::ResetDeclMap
void ResetDeclMap()
Definition: ClangUtilityFunction.h:87
StreamFile.h
lldb_private::ClangUtilityFunction::Install
bool Install(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx) override
Install the utility function into a process.
Definition: ClangUtilityFunction.cpp:80
lldb_private::Status
Definition: Status.h:44
lldb_private::ClangExpressionParser
Definition: ClangExpressionParser.h:45
lldb_private::ClangUtilityFunction::DeclMap
ClangExpressionDeclMap * DeclMap()
Definition: ClangUtilityFunction.h:63
lldb_private::ExecutionContext::GetBestExecutionContextScope
ExecutionContextScope * GetBestExecutionContextScope() const
Definition: ExecutionContext.cpp:216
lldb_private::DiagnosticManager::PutString
size_t void PutString(DiagnosticSeverity severity, llvm::StringRef str)
Definition: DiagnosticManager.cpp:73
lldb_private::UtilityFunction::m_function_text
std::string m_function_text
The text of the function. Must be a well-formed translation unit.
Definition: UtilityFunction.h:117
lldb_private::NativeFile
Definition: File.h:374
lldb_private::DiagnosticManager
Definition: DiagnosticManager.h:93
lldb_private::ClangUtilityFunction::ResetDeclMap
void ResetDeclMap()
Definition: ClangUtilityFunction.h:65
ClangExpressionDeclMap.h
LLDB_INVALID_ADDRESS
#define LLDB_INVALID_ADDRESS
Invalid value definitions.
Definition: lldb-defines.h:85
lldb_private::ExecutionContext::GetTargetSP
const lldb::TargetSP & GetTargetSP() const
Get accessor to get the target shared pointer.
Definition: ExecutionContext.h:453
lldb::eLanguageTypeC
@ eLanguageTypeC
Non-standardized C, such as K&R.
Definition: lldb-enumerations.h:439
lldb_private::ClangExpressionSourceCode
Definition: ClangExpressionSourceCode.h:24
lldb_private
A class that represents a running process on the host machine.
Definition: SBCommandInterpreterRunOptions.h:16
lldb_private::File::eOpenOptionWrite
@ eOpenOptionWrite
Definition: File.h:48
lldb_private::NativeFile::Write
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:539
lldb_private::UtilityFunction::FunctionName
const char * FunctionName() override
Return the function name that should be used for executing the expression.
Definition: UtilityFunction.h:89
ConstString.h
Stream.h
lldb_private::ClangUtilityFunction::ClangUtilityFunctionHelper::m_expr_decl_map_up
std::unique_ptr< ClangExpressionDeclMap > m_expr_decl_map_up
Definition: ClangUtilityFunction.h:103
lldb_private::ClangUtilityFunction::ID
static char ID
Definition: ClangUtilityFunction.h:36
lldb_private::FileSpec::GetFilename
ConstString & GetFilename()
Filename string get accessor.
Definition: FileSpec.cpp:341
lldb_private::ClangExpressionDeclMap::DidParse
void DidParse()
Disable the state needed for parsing and IR transformation.
Definition: ClangExpressionDeclMap.cpp:135
lldb_private::ExecutionContext::GetTargetPtr
Target * GetTargetPtr() const
Returns a pointer to the target object.
Definition: ExecutionContext.cpp:200
ExecutionContext.h
lldb_private::ModuleList::Append
void Append(const lldb::ModuleSP &module_sp, bool notify=true)
Append a module to the module list.
lldb_private::UtilityFunction
Definition: UtilityFunction.h:30
lldb_private::DiagnosticManager::Printf
size_t Printf(DiagnosticSeverity severity, const char *format,...) __attribute__((format(printf
Definition: DiagnosticManager.cpp:59
lldb_private::Status::AsCString
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition: Status.cpp:131