LLDB mainline
ScriptInterpreterPythonImpl.h
Go to the documentation of this file.
1//===-- ScriptInterpreterPythonImpl.h ---------------------------*- C++ -*-===//
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#ifndef LLDB_SOURCE_PLUGINS_SCRIPTINTERPRETER_PYTHON_SCRIPTINTERPRETERPYTHONIMPL_H
10#define LLDB_SOURCE_PLUGINS_SCRIPTINTERPRETER_PYTHON_SCRIPTINTERPRETERPYTHONIMPL_H
11
12#include "lldb-python.h"
13
14#include "PythonDataObjects.h"
16
17#include "lldb/Host/Terminal.h"
19
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/StringRef.h"
22
23namespace lldb_private {
26public:
28
30
32
33 bool Interrupt() override;
34
35 bool ExecuteOneLine(
36 llvm::StringRef command, CommandReturnObject *result,
37 const ExecuteScriptOptions &options = ExecuteScriptOptions()) override;
38
39 void ExecuteInterpreterLoop() override;
40
42 llvm::StringRef in_string,
43 ScriptInterpreter::ScriptReturnType return_type, void *ret_value,
44 const ExecuteScriptOptions &options = ExecuteScriptOptions()) override;
45
47 const char *in_string,
48 const ExecuteScriptOptions &options = ExecuteScriptOptions()) override;
49
50 Status
52
53 bool GenerateTypeScriptFunction(StringList &input, std::string &output,
54 const void *name_token = nullptr) override;
55
56 bool GenerateTypeSynthClass(StringList &input, std::string &output,
57 const void *name_token = nullptr) override;
58
59 bool GenerateTypeSynthClass(const char *oneliner, std::string &output,
60 const void *name_token = nullptr) override;
61
62 // use this if the function code is just a one-liner script
63 bool GenerateTypeScriptFunction(const char *oneliner, std::string &output,
64 const void *name_token = nullptr) override;
65
67 std::string &output) override;
68
70 CreateSyntheticScriptedProvider(const char *class_name,
71 lldb::ValueObjectSP valobj) override;
72
75
77
79
82
85
87
90
92
94
97
100
102
104 LoadPluginModule(const FileSpec &file_spec,
105 lldb_private::Status &error) override;
106
108 GetDynamicSettings(StructuredData::ObjectSP plugin_module_sp, Target *target,
109 const char *setting_name,
110 lldb_private::Status &error) override;
111
112 size_t CalculateNumChildren(const StructuredData::ObjectSP &implementor,
113 uint32_t max) override;
114
116 GetChildAtIndex(const StructuredData::ObjectSP &implementor,
117 uint32_t idx) override;
118
119 llvm::Expected<uint32_t>
121 const char *child_name) override;
122
124 const StructuredData::ObjectSP &implementor) override;
125
127 const StructuredData::ObjectSP &implementor) override;
128
130 GetSyntheticValue(const StructuredData::ObjectSP &implementor) override;
131
133 GetSyntheticTypeName(const StructuredData::ObjectSP &implementor) override;
134
135 bool
136 RunScriptBasedCommand(const char *impl_function, llvm::StringRef args,
137 ScriptedCommandSynchronicity synchronicity,
139 Status &error,
140 const lldb_private::ExecutionContext &exe_ctx) override;
141
142 Status GenerateFunction(const char *signature, const StringList &input,
143 bool is_callback) override;
144
146 std::string &output,
147 bool has_extra_args,
148 bool is_callback) override;
149
151 std::string &output,
152 bool is_callback) override;
153
154 bool GetScriptedSummary(const char *function_name, lldb::ValueObjectSP valobj,
155 StructuredData::ObjectSP &callee_wrapper_sp,
156 const TypeSummaryOptions &options,
157 std::string &retval) override;
158
159 bool FormatterCallbackFunction(const char *function_name,
160 lldb::TypeImplSP type_impl_sp) override;
161
162 bool GetDocumentationForItem(const char *item, std::string &dest) override;
163
164 bool CheckObjectExists(const char *name) override {
165 if (!name || !name[0])
166 return false;
167 std::string temp;
168 return GetDocumentationForItem(name, temp);
169 }
170
171 bool RunScriptFormatKeyword(const char *impl_function, Process *process,
172 std::string &output, Status &error) override;
173
174 bool RunScriptFormatKeyword(const char *impl_function, Thread *thread,
175 std::string &output, Status &error) override;
176
177 bool RunScriptFormatKeyword(const char *impl_function, Target *target,
178 std::string &output, Status &error) override;
179
180 bool RunScriptFormatKeyword(const char *impl_function, StackFrame *frame,
181 std::string &output, Status &error) override;
182
183 bool RunScriptFormatKeyword(const char *impl_function, ValueObject *value,
184 std::string &output, Status &error) override;
185
186 bool LoadScriptingModule(const char *filename,
187 const LoadScriptOptions &options,
189 StructuredData::ObjectSP *module_sp = nullptr,
190 FileSpec extra_search_dir = {},
191 lldb::TargetSP loaded_into_target_sp = {}) override;
192
193 bool IsReservedWord(const char *word) override;
194
195 std::unique_ptr<ScriptInterpreterLocker> AcquireInterpreterLock() override;
196
198 std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
199 CommandReturnObject &result) override;
200
201 void
202 CollectDataForWatchpointCommandCallback(WatchpointOptions *wp_options,
203 CommandReturnObject &result) override;
204
205 /// Set the callback body text into the callback for the breakpoint.
206 Status SetBreakpointCommandCallback(BreakpointOptions &bp_options,
207 const char *callback_body,
208 bool is_callback) override;
209
211 BreakpointOptions &bp_options, const char *function_name,
212 StructuredData::ObjectSP extra_args_sp) override;
213
214 /// This one is for deserialization:
216 BreakpointOptions &bp_options,
217 std::unique_ptr<BreakpointOptions::CommandData> &data_up) override;
218
219 Status SetBreakpointCommandCallback(BreakpointOptions &bp_options,
220 const char *command_body_text,
221 StructuredData::ObjectSP extra_args_sp,
222 bool uses_extra_args, bool is_callback);
223
224 /// Set a one-liner as the callback for the watchpoint.
225 void SetWatchpointCommandCallback(WatchpointOptions *wp_options,
226 const char *user_input,
227 bool is_callback) override;
228
229 const char *GetDictionaryName() { return m_dictionary_name.c_str(); }
230
231 PyThreadState *GetThreadState() { return m_command_thread_state; }
232
233 void SetThreadState(PyThreadState *s) {
234 if (s)
236 }
237
238 // IOHandlerDelegate
239 void IOHandlerActivated(IOHandler &io_handler, bool interactive) override;
240
241 void IOHandlerInputComplete(IOHandler &io_handler,
242 std::string &data) override;
243
245
246 // PluginInterface protocol
247 llvm::StringRef GetPluginName() override { return GetPluginNameStatic(); }
248
250 public:
251 enum OnEntry {
252 AcquireLock = 0x0001,
253 InitSession = 0x0002,
254 InitGlobals = 0x0004,
255 NoSTDIN = 0x0008,
256 // Keep sys.stdout/stderr on the real terminal instead of routing them
257 // through the output-lock pipe (see EnterSession). Set by the interactive
258 // interpreter, whose input() needs both the real stdin and stdout for
259 // readline-based line editing and echo.
261 };
262
263 enum OnLeave {
264 FreeLock = 0x0001,
265 FreeAcquiredLock = 0x0002, // do not free the lock if we already held it
266 // when calling constructor
268 };
269
270 Locker(ScriptInterpreterPythonImpl *py_interpreter,
271 uint16_t on_entry = AcquireLock | InitSession,
272 uint16_t on_leave = FreeLock | TearDownSession,
273 lldb::FileSP in = nullptr, lldb::FileSP out = nullptr,
274 lldb::FileSP err = nullptr);
275
276 ~Locker() override;
277
278 private:
279 bool DoAcquireLock();
280
281 bool DoInitSession(uint16_t on_entry_flags, lldb::FileSP in,
282 lldb::FileSP out, lldb::FileSP err);
283
284 bool DoFreeLock();
285
286 bool DoTearDownSession();
287
290 PyGILState_STATE m_GILState;
291 };
292
293 static bool BreakpointCallbackFunction(void *baton,
295 lldb::user_id_t break_id,
296 lldb::user_id_t break_loc_id);
297 static bool WatchpointCallbackFunction(void *baton,
299 lldb::user_id_t watch_id);
300 static void Initialize();
301
313
314 enum class AddLocation { Beginning, End };
315
316 static void AddToSysPath(AddLocation location, std::string path);
317
318 bool EnterSession(uint16_t on_entry_flags, lldb::FileSP in, lldb::FileSP out,
319 lldb::FileSP err);
320
321 void LeaveSession();
322
323 uint32_t IsExecutingPython() {
324 std::lock_guard<std::mutex> guard(m_mutex);
325 return m_lock_count > 0;
326 }
327
329 std::lock_guard<std::mutex> guard(m_mutex);
330 return ++m_lock_count;
331 }
332
334 std::lock_guard<std::mutex> guard(m_mutex);
335 if (m_lock_count > 0)
336 --m_lock_count;
337 return m_lock_count;
338 }
339
345
347
349
351
352 llvm::Expected<unsigned> GetMaxPositionalArgumentsForCallable(
353 const llvm::StringRef &callable_name) override;
354
356
357 /// Point sys.\p py_name at \p file. When \p serialize_terminal_output is true
358 /// and \p file is the debugger's own terminal, the output is routed through a
359 /// lock-synchronized pipe instead (see RedirectTerminalHandleThroughLock) so
360 /// it cannot race the statusline redraw.
361 bool SetStdHandle(lldb::FileSP file, const char *py_name,
362 python::PythonObject &save_file, const char *mode,
363 bool serialize_terminal_output);
364
365 /// Pipe-backed sys.stdout/stderr whose writes are serialized against the
366 /// statusline redraw. Defined and documented in the implementation file.
367 class SessionIORedirect;
368
369 /// If \p file is the debugger's own terminal, point sys.\p py_name at a
370 /// pipe-backed file whose writes are serialized through the output lock (see
371 /// SessionIORedirect) and return true. Return false to let SetStdHandle wrap
372 /// \p file normally.
373 bool RedirectTerminalHandleThroughLock(const char *py_name,
374 python::PythonObject &save_file,
375 const char *mode, File &file);
376
380 std::unique_ptr<SessionIORedirect> m_stdout_redirect;
381 std::unique_ptr<SessionIORedirect> m_stderr_redirect;
387 std::string m_dictionary_name;
392 uint32_t m_lock_count;
393 std::mutex m_mutex;
395};
396
398public:
403
404 ~IOHandlerPythonInterpreter() override = default;
405
406 llvm::StringRef GetControlSequence(char ch) override {
407 static constexpr llvm::StringLiteral control_sequence("quit()\n");
408 if (ch == 'd')
409 return control_sequence;
410 return {};
411 }
412
413 void Run() override {
414 if (m_python) {
415 int stdin_fd = GetInputFD();
416 if (stdin_fd >= 0) {
417 Terminal terminal(stdin_fd);
418 TerminalState terminal_state(terminal);
419
420 if (terminal.IsATerminal()) {
421 // FIXME: error handling?
422 llvm::consumeError(terminal.SetCanonical(false));
423 llvm::consumeError(terminal.SetEcho(true));
424 }
425
427 m_python,
434
435 // The following call drops into the embedded interpreter loop and
436 // stays there until the user chooses to exit from the Python
437 // interpreter. This embedded interpreter will, as any Python code that
438 // performs I/O, unlock the GIL before a system call that can hang, and
439 // lock it when the syscall has returned.
440
441 // We need to surround the call to the embedded interpreter with calls
442 // to PyGILState_Ensure and PyGILState_Release (using the Locker
443 // above). This is because Python has a global lock which must be held
444 // whenever we want to touch any Python objects. Otherwise, if the user
445 // calls Python code, the interpreter state will be off, and things
446 // could hang (it's happened before).
447
448 StreamString run_string;
449 run_string.Printf("run_python_interpreter (%s)",
450 m_python->GetDictionaryName());
451 python::RunSimpleString(run_string.GetData());
452 }
453 }
454 SetIsDone(true);
455 }
456
457 void Cancel() override {}
458
459 bool Interrupt() override { return m_python->Interrupt(); }
460
461 void GotEOF() override {}
462
463protected:
465};
466
467} // namespace lldb_private
468
469#endif // LLDB_SOURCE_PLUGINS_SCRIPTINTERPRETER_PYTHON_SCRIPTINTERPRETERPYTHONIMPL_H
static llvm::raw_ostream & error(Stream &strm)
ScriptInterpreterPythonImpl::Locker Locker
A uniqued constant string class.
Definition ConstString.h:40
A class to manage flag bits.
Definition Debugger.h:100
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
A file utility class.
Definition FileSpec.h:57
An abstract base class for files.
Definition FileBase.h:34
~IOHandlerPythonInterpreter() override=default
llvm::StringRef GetControlSequence(char ch) override
IOHandlerPythonInterpreter(Debugger &debugger, ScriptInterpreterPythonImpl *python)
IOHandler(Debugger &debugger, IOHandler::Type type)
Definition IOHandler.cpp:55
void SetIsDone(bool b)
Definition IOHandler.h:81
A plug-in interface definition class for debugging a process.
Definition Process.h:359
bool DoInitSession(uint16_t on_entry_flags, lldb::FileSP in, lldb::FileSP out, lldb::FileSP err)
Locker(ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry=AcquireLock|InitSession, uint16_t on_leave=FreeLock|TearDownSession, lldb::FileSP in=nullptr, lldb::FileSP out=nullptr, lldb::FileSP err=nullptr)
SynchronicityHandler(lldb::DebuggerSP, ScriptedCommandSynchronicity)
bool GenerateTypeScriptFunction(StringList &input, std::string &output, const void *name_token=nullptr) override
Status GenerateFunction(const char *signature, const StringList &input, bool is_callback) override
bool GenerateScriptAliasFunction(StringList &input, std::string &output) override
lldb_private::Status ExecuteMultipleLines(const char *in_string, const ExecuteScriptOptions &options=ExecuteScriptOptions()) override
bool GenerateWatchpointCommandCallbackData(StringList &input, std::string &output, bool is_callback) override
Status SetBreakpointCommandCallbackFunction(BreakpointOptions &bp_options, const char *function_name, StructuredData::ObjectSP extra_args_sp) override
Set a script function as the callback for the breakpoint.
lldb::ScriptedThreadInterfaceSP CreateScriptedThreadInterface() override
std::unique_ptr< SessionIORedirect > m_stderr_redirect
static bool BreakpointCallbackFunction(void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
StructuredData::DictionarySP GetDynamicSettings(StructuredData::ObjectSP plugin_module_sp, Target *target, const char *setting_name, lldb_private::Status &error) override
void CollectDataForWatchpointCommandCallback(WatchpointOptions *wp_options, CommandReturnObject &result) override
lldb::ScriptedCommandInterfaceSP CreateScriptedCommandInterface() override
bool RunScriptBasedCommand(const char *impl_function, llvm::StringRef args, ScriptedCommandSynchronicity synchronicity, lldb_private::CommandReturnObject &cmd_retobj, Status &error, const lldb_private::ExecutionContext &exe_ctx) override
lldb::ScriptedFrameProviderInterfaceSP CreateScriptedFrameProviderInterface() override
Status SetBreakpointCommandCallback(BreakpointOptions &bp_options, const char *callback_body, bool is_callback) override
Set the callback body text into the callback for the breakpoint.
lldb::ScriptedStackFrameRecognizerInterfaceSP CreateScriptedStackFrameRecognizerInterface() override
bool EnterSession(uint16_t on_entry_flags, lldb::FileSP in, lldb::FileSP out, lldb::FileSP err)
void SetWatchpointCommandCallback(WatchpointOptions *wp_options, const char *user_input, bool is_callback) override
Set a one-liner as the callback for the watchpoint.
bool RedirectTerminalHandleThroughLock(const char *py_name, python::PythonObject &save_file, const char *mode, File &file)
If file is the debugger's own terminal, point sys.
lldb::ValueObjectSP GetSyntheticValue(const StructuredData::ObjectSP &implementor) override
std::unique_ptr< ScriptInterpreterLocker > AcquireInterpreterLock() override
void CollectDataForBreakpointCommandCallback(std::vector< std::reference_wrapper< BreakpointOptions > > &bp_options_vec, CommandReturnObject &result) override
bool UpdateSynthProviderInstance(const StructuredData::ObjectSP &implementor) override
static void AddToSysPath(AddLocation location, std::string path)
lldb::ScriptedStringSummaryInterfaceSP CreateScriptedStringSummaryInterface() override
bool MightHaveChildrenSynthProviderInstance(const StructuredData::ObjectSP &implementor) override
bool LoadScriptingModule(const char *filename, const LoadScriptOptions &options, lldb_private::Status &error, StructuredData::ObjectSP *module_sp=nullptr, FileSpec extra_search_dir={}, lldb::TargetSP loaded_into_target_sp={}) override
ConstString GetSyntheticTypeName(const StructuredData::ObjectSP &implementor) override
Status GenerateBreakpointCommandCallbackData(StringList &input, std::string &output, bool has_extra_args, bool is_callback) override
lldb::OperatingSystemInterfaceSP CreateOperatingSystemInterface() override
llvm::Expected< uint32_t > GetIndexOfChildWithName(const StructuredData::ObjectSP &implementor, const char *child_name) override
bool FormatterCallbackFunction(const char *function_name, lldb::TypeImplSP type_impl_sp) override
Status ExportFunctionDefinitionToInterpreter(StringList &function_def) override
StructuredData::ObjectSP CreateSyntheticScriptedProvider(const char *class_name, lldb::ValueObjectSP valobj) override
bool ExecuteOneLine(llvm::StringRef command, CommandReturnObject *result, const ExecuteScriptOptions &options=ExecuteScriptOptions()) override
bool GetDocumentationForItem(const char *item, std::string &dest) override
In Python, a special attribute doc contains the docstring for an object (function,...
lldb::ScriptedHookInterfaceSP CreateScriptedHookInterface() override
void IOHandlerInputComplete(IOHandler &io_handler, std::string &data) override
Called when a line or lines have been retrieved.
void IOHandlerActivated(IOHandler &io_handler, bool interactive) override
bool GetScriptedSummary(const char *function_name, lldb::ValueObjectSP valobj, StructuredData::ObjectSP &callee_wrapper_sp, const TypeSummaryOptions &options, std::string &retval) override
lldb::ScriptedFrameInterfaceSP CreateScriptedFrameInterface() override
lldb::ScriptedProcessInterfaceUP CreateScriptedProcessInterface() override
size_t CalculateNumChildren(const StructuredData::ObjectSP &implementor, uint32_t max) override
bool ExecuteOneLineWithReturn(llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type, void *ret_value, const ExecuteScriptOptions &options=ExecuteScriptOptions()) override
lldb::ScriptedBreakpointInterfaceSP CreateScriptedBreakpointInterface() override
bool RunScriptFormatKeyword(const char *impl_function, Process *process, std::string &output, Status &error) override
bool SetStdHandle(lldb::FileSP file, const char *py_name, python::PythonObject &save_file, const char *mode, bool serialize_terminal_output)
Point sys.
lldb::ValueObjectSP GetChildAtIndex(const StructuredData::ObjectSP &implementor, uint32_t idx) override
bool GenerateTypeSynthClass(StringList &input, std::string &output, const void *name_token=nullptr) override
StructuredData::ObjectSP CreateStructuredDataFromScriptObject(ScriptObject obj) override
StructuredData::ObjectSP LoadPluginModule(const FileSpec &file_spec, lldb_private::Status &error) override
llvm::Expected< unsigned > GetMaxPositionalArgumentsForCallable(const llvm::StringRef &callable_name) override
static bool WatchpointCallbackFunction(void *baton, StoppointCallbackContext *context, lldb::user_id_t watch_id)
static lldb::ScriptInterpreterSP CreateInstance(Debugger &debugger)
lldb::ScriptedThreadPlanInterfaceSP CreateScriptedThreadPlanInterface() override
std::unique_ptr< SessionIORedirect > m_stdout_redirect
This base class provides an interface to stack frames.
Definition StackFrame.h:44
An error handling class.
Definition Status.h:118
General Outline: When we hit a breakpoint we need to package up whatever information is needed to eva...
const char * GetData() const
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
std::shared_ptr< Dictionary > DictionarySP
std::shared_ptr< Object > ObjectSP
A RAII-friendly terminal state saving/restoring class.
Definition Terminal.h:99
llvm::Error SetEcho(bool enabled)
Definition Terminal.cpp:80
llvm::Error SetCanonical(bool enabled)
Definition Terminal.cpp:96
bool IsATerminal() const
Definition Terminal.cpp:35
int RunSimpleString(const char *str)
A class that represents a running process on the host machine.
std::shared_ptr< lldb_private::ScriptedHookInterface > ScriptedHookInterfaceSP
std::shared_ptr< lldb_private::ScriptedStringSummaryInterface > ScriptedStringSummaryInterfaceSP
std::shared_ptr< lldb_private::ScriptInterpreter > ScriptInterpreterSP
std::shared_ptr< lldb_private::ScriptedThreadPlanInterface > ScriptedThreadPlanInterfaceSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
std::shared_ptr< lldb_private::OperatingSystemInterface > OperatingSystemInterfaceSP
std::shared_ptr< lldb_private::ScriptedBreakpointInterface > ScriptedBreakpointInterfaceSP
std::shared_ptr< lldb_private::ScriptedThreadInterface > ScriptedThreadInterfaceSP
std::shared_ptr< lldb_private::Debugger > DebuggerSP
std::shared_ptr< lldb_private::ScriptedFrameProviderInterface > ScriptedFrameProviderInterfaceSP
std::shared_ptr< lldb_private::ScriptedCommandInterface > ScriptedCommandInterfaceSP
uint64_t user_id_t
Definition lldb-types.h:82
std::shared_ptr< lldb_private::TypeImpl > TypeImplSP
std::shared_ptr< lldb_private::Target > TargetSP
std::shared_ptr< lldb_private::File > FileSP
std::shared_ptr< lldb_private::ScriptedStackFrameRecognizerInterface > ScriptedStackFrameRecognizerInterfaceSP
std::unique_ptr< lldb_private::ScriptedProcessInterface > ScriptedProcessInterfaceUP
std::shared_ptr< lldb_private::ScriptedFrameInterface > ScriptedFrameInterfaceSP