xref: /llvm-project/lldb/source/Interpreter/ScriptInterpreter.cpp (revision 9a9fce1fed6d2af3fb6d1d7073c4a0b3e00bc515)
1 //===-- ScriptInterpreter.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/Interpreter/ScriptInterpreter.h"
10 #include "lldb/Core/Debugger.h"
11 #include "lldb/Host/ConnectionFileDescriptor.h"
12 #include "lldb/Host/Pipe.h"
13 #include "lldb/Host/PseudoTerminal.h"
14 #include "lldb/Interpreter/CommandReturnObject.h"
15 #include "lldb/Utility/Status.h"
16 #include "lldb/Utility/Stream.h"
17 #include "lldb/Utility/StringList.h"
18 #if defined(_WIN32)
19 #include "lldb/Host/windows/ConnectionGenericFileWindows.h"
20 #endif
21 #include <cstdio>
22 #include <cstdlib>
23 #include <memory>
24 #include <optional>
25 #include <string>
26 
27 using namespace lldb;
28 using namespace lldb_private;
29 
30 ScriptInterpreter::ScriptInterpreter(
31     Debugger &debugger, lldb::ScriptLanguage script_lang,
32     lldb::ScriptedPlatformInterfaceUP scripted_platform_interface_up)
33     : m_debugger(debugger), m_script_lang(script_lang),
34       m_scripted_platform_interface_up(
35           std::move(scripted_platform_interface_up)) {}
36 
37 void ScriptInterpreter::CollectDataForBreakpointCommandCallback(
38     std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
39     CommandReturnObject &result) {
40   result.AppendError(
41       "This script interpreter does not support breakpoint callbacks.");
42 }
43 
44 void ScriptInterpreter::CollectDataForWatchpointCommandCallback(
45     WatchpointOptions *bp_options, CommandReturnObject &result) {
46   result.AppendError(
47       "This script interpreter does not support watchpoint callbacks.");
48 }
49 
50 StructuredData::DictionarySP ScriptInterpreter::GetInterpreterInfo() {
51   return nullptr;
52 }
53 
54 bool ScriptInterpreter::LoadScriptingModule(const char *filename,
55                                             const LoadScriptOptions &options,
56                                             lldb_private::Status &error,
57                                             StructuredData::ObjectSP *module_sp,
58                                             FileSpec extra_search_dir) {
59   error.SetErrorString(
60       "This script interpreter does not support importing modules.");
61   return false;
62 }
63 
64 std::string ScriptInterpreter::LanguageToString(lldb::ScriptLanguage language) {
65   switch (language) {
66   case eScriptLanguageNone:
67     return "None";
68   case eScriptLanguagePython:
69     return "Python";
70   case eScriptLanguageLua:
71     return "Lua";
72   case eScriptLanguageUnknown:
73     return "Unknown";
74   }
75   llvm_unreachable("Unhandled ScriptInterpreter!");
76 }
77 
78 lldb::DataExtractorSP
79 ScriptInterpreter::GetDataExtractorFromSBData(const lldb::SBData &data) const {
80   return data.m_opaque_sp;
81 }
82 
83 Status
84 ScriptInterpreter::GetStatusFromSBError(const lldb::SBError &error) const {
85   if (error.m_opaque_up)
86     return *error.m_opaque_up;
87 
88   return Status();
89 }
90 
91 std::optional<MemoryRegionInfo>
92 ScriptInterpreter::GetOpaqueTypeFromSBMemoryRegionInfo(
93     const lldb::SBMemoryRegionInfo &mem_region) const {
94   if (!mem_region.m_opaque_up)
95     return std::nullopt;
96   return *mem_region.m_opaque_up.get();
97 }
98 
99 lldb::ScriptLanguage
100 ScriptInterpreter::StringToLanguage(const llvm::StringRef &language) {
101   if (language.equals_insensitive(LanguageToString(eScriptLanguageNone)))
102     return eScriptLanguageNone;
103   if (language.equals_insensitive(LanguageToString(eScriptLanguagePython)))
104     return eScriptLanguagePython;
105   if (language.equals_insensitive(LanguageToString(eScriptLanguageLua)))
106     return eScriptLanguageLua;
107   return eScriptLanguageUnknown;
108 }
109 
110 Status ScriptInterpreter::SetBreakpointCommandCallback(
111     std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
112     const char *callback_text) {
113   Status error;
114   for (BreakpointOptions &bp_options : bp_options_vec) {
115     error = SetBreakpointCommandCallback(bp_options, callback_text,
116                                          /*is_callback=*/false);
117     if (!error.Success())
118       break;
119   }
120   return error;
121 }
122 
123 Status ScriptInterpreter::SetBreakpointCommandCallbackFunction(
124     std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
125     const char *function_name, StructuredData::ObjectSP extra_args_sp) {
126   Status error;
127   for (BreakpointOptions &bp_options : bp_options_vec) {
128     error = SetBreakpointCommandCallbackFunction(bp_options, function_name,
129                                                  extra_args_sp);
130     if (!error.Success())
131       return error;
132   }
133   return error;
134 }
135 
136 std::unique_ptr<ScriptInterpreterLocker>
137 ScriptInterpreter::AcquireInterpreterLock() {
138   return std::make_unique<ScriptInterpreterLocker>();
139 }
140 
141 static void ReadThreadBytesReceived(void *baton, const void *src,
142                                     size_t src_len) {
143   if (src && src_len) {
144     Stream *strm = (Stream *)baton;
145     strm->Write(src, src_len);
146     strm->Flush();
147   }
148 }
149 
150 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
151 ScriptInterpreterIORedirect::Create(bool enable_io, Debugger &debugger,
152                                     CommandReturnObject *result) {
153   if (enable_io)
154     return std::unique_ptr<ScriptInterpreterIORedirect>(
155         new ScriptInterpreterIORedirect(debugger, result));
156 
157   auto nullin = FileSystem::Instance().Open(FileSpec(FileSystem::DEV_NULL),
158                                             File::eOpenOptionReadOnly);
159   if (!nullin)
160     return nullin.takeError();
161 
162   auto nullout = FileSystem::Instance().Open(FileSpec(FileSystem::DEV_NULL),
163                                              File::eOpenOptionWriteOnly);
164   if (!nullout)
165     return nullin.takeError();
166 
167   return std::unique_ptr<ScriptInterpreterIORedirect>(
168       new ScriptInterpreterIORedirect(std::move(*nullin), std::move(*nullout)));
169 }
170 
171 ScriptInterpreterIORedirect::ScriptInterpreterIORedirect(
172     std::unique_ptr<File> input, std::unique_ptr<File> output)
173     : m_input_file_sp(std::move(input)),
174       m_output_file_sp(std::make_shared<StreamFile>(std::move(output))),
175       m_error_file_sp(m_output_file_sp),
176       m_communication("lldb.ScriptInterpreterIORedirect.comm"),
177       m_disconnect(false) {}
178 
179 ScriptInterpreterIORedirect::ScriptInterpreterIORedirect(
180     Debugger &debugger, CommandReturnObject *result)
181     : m_communication("lldb.ScriptInterpreterIORedirect.comm"),
182       m_disconnect(false) {
183 
184   if (result) {
185     m_input_file_sp = debugger.GetInputFileSP();
186 
187     Pipe pipe;
188     Status pipe_result = pipe.CreateNew(false);
189 #if defined(_WIN32)
190     lldb::file_t read_file = pipe.GetReadNativeHandle();
191     pipe.ReleaseReadFileDescriptor();
192     std::unique_ptr<ConnectionGenericFile> conn_up =
193         std::make_unique<ConnectionGenericFile>(read_file, true);
194 #else
195     std::unique_ptr<ConnectionFileDescriptor> conn_up =
196         std::make_unique<ConnectionFileDescriptor>(
197             pipe.ReleaseReadFileDescriptor(), true);
198 #endif
199 
200     if (conn_up->IsConnected()) {
201       m_communication.SetConnection(std::move(conn_up));
202       m_communication.SetReadThreadBytesReceivedCallback(
203           ReadThreadBytesReceived, &result->GetOutputStream());
204       m_communication.StartReadThread();
205       m_disconnect = true;
206 
207       FILE *outfile_handle = fdopen(pipe.ReleaseWriteFileDescriptor(), "w");
208       m_output_file_sp = std::make_shared<StreamFile>(outfile_handle, true);
209       m_error_file_sp = m_output_file_sp;
210       if (outfile_handle)
211         ::setbuf(outfile_handle, nullptr);
212 
213       result->SetImmediateOutputFile(debugger.GetOutputStream().GetFileSP());
214       result->SetImmediateErrorFile(debugger.GetErrorStream().GetFileSP());
215     }
216   }
217 
218   if (!m_input_file_sp || !m_output_file_sp || !m_error_file_sp)
219     debugger.AdoptTopIOHandlerFilesIfInvalid(m_input_file_sp, m_output_file_sp,
220                                              m_error_file_sp);
221 }
222 
223 void ScriptInterpreterIORedirect::Flush() {
224   if (m_output_file_sp)
225     m_output_file_sp->Flush();
226   if (m_error_file_sp)
227     m_error_file_sp->Flush();
228 }
229 
230 ScriptInterpreterIORedirect::~ScriptInterpreterIORedirect() {
231   if (!m_disconnect)
232     return;
233 
234   assert(m_output_file_sp);
235   assert(m_error_file_sp);
236   assert(m_output_file_sp == m_error_file_sp);
237 
238   // Close the write end of the pipe since we are done with our one line
239   // script. This should cause the read thread that output_comm is using to
240   // exit.
241   m_output_file_sp->GetFile().Close();
242   // The close above should cause this thread to exit when it gets to the end
243   // of file, so let it get all its data.
244   m_communication.JoinReadThread();
245   // Now we can close the read end of the pipe.
246   m_communication.Disconnect();
247 }
248