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_PLUGINS_SCRIPTINTERPRETER_PYTHON_SCRIPTINTERPRETERPYTHONIMPL_H 10 #define LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_SCRIPTINTERPRETERPYTHONIMPL_H 11 12 #include "lldb/Host/Config.h" 13 14 #if LLDB_ENABLE_PYTHON 15 16 #include "lldb-python.h" 17 18 #include "PythonDataObjects.h" 19 #include "ScriptInterpreterPython.h" 20 21 #include "lldb/Host/Terminal.h" 22 #include "lldb/Utility/StreamString.h" 23 24 #include "llvm/ADT/STLExtras.h" 25 #include "llvm/ADT/StringRef.h" 26 27 namespace lldb_private { 28 class IOHandlerPythonInterpreter; 29 class ScriptInterpreterPythonImpl : public ScriptInterpreterPython { 30 public: 31 friend class IOHandlerPythonInterpreter; 32 33 ScriptInterpreterPythonImpl(Debugger &debugger); 34 35 ~ScriptInterpreterPythonImpl() override; 36 37 bool Interrupt() override; 38 39 bool ExecuteOneLine( 40 llvm::StringRef command, CommandReturnObject *result, 41 const ExecuteScriptOptions &options = ExecuteScriptOptions()) override; 42 43 void ExecuteInterpreterLoop() override; 44 45 bool ExecuteOneLineWithReturn( 46 llvm::StringRef in_string, 47 ScriptInterpreter::ScriptReturnType return_type, void *ret_value, 48 const ExecuteScriptOptions &options = ExecuteScriptOptions()) override; 49 50 lldb_private::Status ExecuteMultipleLines( 51 const char *in_string, 52 const ExecuteScriptOptions &options = ExecuteScriptOptions()) override; 53 54 Status 55 ExportFunctionDefinitionToInterpreter(StringList &function_def) override; 56 57 bool GenerateTypeScriptFunction(StringList &input, std::string &output, 58 const void *name_token = nullptr) override; 59 60 bool GenerateTypeSynthClass(StringList &input, std::string &output, 61 const void *name_token = nullptr) override; 62 63 bool GenerateTypeSynthClass(const char *oneliner, std::string &output, 64 const void *name_token = nullptr) override; 65 66 // use this if the function code is just a one-liner script 67 bool GenerateTypeScriptFunction(const char *oneliner, std::string &output, 68 const void *name_token = nullptr) override; 69 70 bool GenerateScriptAliasFunction(StringList &input, 71 std::string &output) override; 72 73 StructuredData::ObjectSP 74 CreateSyntheticScriptedProvider(const char *class_name, 75 lldb::ValueObjectSP valobj) override; 76 77 StructuredData::GenericSP 78 CreateScriptCommandObject(const char *class_name) override; 79 80 StructuredData::ObjectSP 81 CreateStructuredDataFromScriptObject(ScriptObject obj) override; 82 83 StructuredData::GenericSP 84 CreateScriptedBreakpointResolver(const char *class_name, 85 const StructuredDataImpl &args_data, 86 lldb::BreakpointSP &bkpt_sp) override; 87 bool ScriptedBreakpointResolverSearchCallback( 88 StructuredData::GenericSP implementor_sp, 89 SymbolContext *sym_ctx) override; 90 91 lldb::SearchDepth ScriptedBreakpointResolverSearchDepth( 92 StructuredData::GenericSP implementor_sp) override; 93 94 StructuredData::GenericSP 95 CreateFrameRecognizer(const char *class_name) override; 96 97 lldb::ValueObjectListSP 98 GetRecognizedArguments(const StructuredData::ObjectSP &implementor, 99 lldb::StackFrameSP frame_sp) override; 100 101 bool ShouldHide(const StructuredData::ObjectSP &implementor, 102 lldb::StackFrameSP frame_sp) override; 103 104 lldb::ScriptedProcessInterfaceUP CreateScriptedProcessInterface() override; 105 106 lldb::ScriptedStopHookInterfaceSP CreateScriptedStopHookInterface() override; 107 108 lldb::ScriptedThreadInterfaceSP CreateScriptedThreadInterface() override; 109 110 lldb::ScriptedThreadPlanInterfaceSP 111 CreateScriptedThreadPlanInterface() override; 112 113 lldb::OperatingSystemInterfaceSP CreateOperatingSystemInterface() override; 114 115 StructuredData::ObjectSP 116 LoadPluginModule(const FileSpec &file_spec, 117 lldb_private::Status &error) override; 118 119 StructuredData::DictionarySP 120 GetDynamicSettings(StructuredData::ObjectSP plugin_module_sp, Target *target, 121 const char *setting_name, 122 lldb_private::Status &error) override; 123 124 size_t CalculateNumChildren(const StructuredData::ObjectSP &implementor, 125 uint32_t max) override; 126 127 lldb::ValueObjectSP 128 GetChildAtIndex(const StructuredData::ObjectSP &implementor, 129 uint32_t idx) override; 130 131 int GetIndexOfChildWithName(const StructuredData::ObjectSP &implementor, 132 const char *child_name) override; 133 134 bool UpdateSynthProviderInstance( 135 const StructuredData::ObjectSP &implementor) override; 136 137 bool MightHaveChildrenSynthProviderInstance( 138 const StructuredData::ObjectSP &implementor) override; 139 140 lldb::ValueObjectSP 141 GetSyntheticValue(const StructuredData::ObjectSP &implementor) override; 142 143 ConstString 144 GetSyntheticTypeName(const StructuredData::ObjectSP &implementor) override; 145 146 bool 147 RunScriptBasedCommand(const char *impl_function, llvm::StringRef args, 148 ScriptedCommandSynchronicity synchronicity, 149 lldb_private::CommandReturnObject &cmd_retobj, 150 Status &error, 151 const lldb_private::ExecutionContext &exe_ctx) override; 152 153 bool RunScriptBasedCommand( 154 StructuredData::GenericSP impl_obj_sp, llvm::StringRef args, 155 ScriptedCommandSynchronicity synchronicity, 156 lldb_private::CommandReturnObject &cmd_retobj, Status &error, 157 const lldb_private::ExecutionContext &exe_ctx) override; 158 159 bool RunScriptBasedParsedCommand( 160 StructuredData::GenericSP impl_obj_sp, Args &args, 161 ScriptedCommandSynchronicity synchronicity, 162 lldb_private::CommandReturnObject &cmd_retobj, Status &error, 163 const lldb_private::ExecutionContext &exe_ctx) override; 164 165 std::optional<std::string> 166 GetRepeatCommandForScriptedCommand(StructuredData::GenericSP impl_obj_sp, 167 Args &args) override; 168 169 Status GenerateFunction(const char *signature, const StringList &input, 170 bool is_callback) override; 171 172 Status GenerateBreakpointCommandCallbackData(StringList &input, 173 std::string &output, 174 bool has_extra_args, 175 bool is_callback) override; 176 177 bool GenerateWatchpointCommandCallbackData(StringList &input, 178 std::string &output, 179 bool is_callback) override; 180 181 bool GetScriptedSummary(const char *function_name, lldb::ValueObjectSP valobj, 182 StructuredData::ObjectSP &callee_wrapper_sp, 183 const TypeSummaryOptions &options, 184 std::string &retval) override; 185 186 bool FormatterCallbackFunction(const char *function_name, 187 lldb::TypeImplSP type_impl_sp) override; 188 189 bool GetDocumentationForItem(const char *item, std::string &dest) override; 190 191 bool GetShortHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp, 192 std::string &dest) override; 193 194 uint32_t 195 GetFlagsForCommandObject(StructuredData::GenericSP cmd_obj_sp) override; 196 197 bool GetLongHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp, 198 std::string &dest) override; 199 200 StructuredData::ObjectSP 201 GetOptionsForCommandObject(StructuredData::GenericSP cmd_obj_sp) override; 202 203 StructuredData::ObjectSP 204 GetArgumentsForCommandObject(StructuredData::GenericSP cmd_obj_sp) override; 205 206 bool SetOptionValueForCommandObject(StructuredData::GenericSP cmd_obj_sp, 207 ExecutionContext *exe_ctx, 208 llvm::StringRef long_option, 209 llvm::StringRef value) override; 210 211 void OptionParsingStartedForCommandObject( 212 StructuredData::GenericSP cmd_obj_sp) override; 213 214 bool CheckObjectExists(const char *name) override { 215 if (!name || !name[0]) 216 return false; 217 std::string temp; 218 return GetDocumentationForItem(name, temp); 219 } 220 221 bool RunScriptFormatKeyword(const char *impl_function, Process *process, 222 std::string &output, Status &error) override; 223 224 bool RunScriptFormatKeyword(const char *impl_function, Thread *thread, 225 std::string &output, Status &error) override; 226 227 bool RunScriptFormatKeyword(const char *impl_function, Target *target, 228 std::string &output, Status &error) override; 229 230 bool RunScriptFormatKeyword(const char *impl_function, StackFrame *frame, 231 std::string &output, Status &error) override; 232 233 bool RunScriptFormatKeyword(const char *impl_function, ValueObject *value, 234 std::string &output, Status &error) override; 235 236 bool LoadScriptingModule(const char *filename, 237 const LoadScriptOptions &options, 238 lldb_private::Status &error, 239 StructuredData::ObjectSP *module_sp = nullptr, 240 FileSpec extra_search_dir = {}) override; 241 242 bool IsReservedWord(const char *word) override; 243 244 std::unique_ptr<ScriptInterpreterLocker> AcquireInterpreterLock() override; 245 246 void CollectDataForBreakpointCommandCallback( 247 std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec, 248 CommandReturnObject &result) override; 249 250 void 251 CollectDataForWatchpointCommandCallback(WatchpointOptions *wp_options, 252 CommandReturnObject &result) override; 253 254 /// Set the callback body text into the callback for the breakpoint. 255 Status SetBreakpointCommandCallback(BreakpointOptions &bp_options, 256 const char *callback_body, 257 bool is_callback) override; 258 259 Status SetBreakpointCommandCallbackFunction( 260 BreakpointOptions &bp_options, const char *function_name, 261 StructuredData::ObjectSP extra_args_sp) override; 262 263 /// This one is for deserialization: 264 Status SetBreakpointCommandCallback( 265 BreakpointOptions &bp_options, 266 std::unique_ptr<BreakpointOptions::CommandData> &data_up) override; 267 268 Status SetBreakpointCommandCallback(BreakpointOptions &bp_options, 269 const char *command_body_text, 270 StructuredData::ObjectSP extra_args_sp, 271 bool uses_extra_args, 272 bool is_callback); 273 274 /// Set a one-liner as the callback for the watchpoint. 275 void SetWatchpointCommandCallback(WatchpointOptions *wp_options, 276 const char *user_input, 277 bool is_callback) override; 278 279 const char *GetDictionaryName() { return m_dictionary_name.c_str(); } 280 281 PyThreadState *GetThreadState() { return m_command_thread_state; } 282 283 void SetThreadState(PyThreadState *s) { 284 if (s) 285 m_command_thread_state = s; 286 } 287 288 // IOHandlerDelegate 289 void IOHandlerActivated(IOHandler &io_handler, bool interactive) override; 290 291 void IOHandlerInputComplete(IOHandler &io_handler, 292 std::string &data) override; 293 294 static lldb::ScriptInterpreterSP CreateInstance(Debugger &debugger); 295 296 // PluginInterface protocol 297 llvm::StringRef GetPluginName() override { return GetPluginNameStatic(); } 298 299 class Locker : public ScriptInterpreterLocker { 300 public: 301 enum OnEntry { 302 AcquireLock = 0x0001, 303 InitSession = 0x0002, 304 InitGlobals = 0x0004, 305 NoSTDIN = 0x0008 306 }; 307 308 enum OnLeave { 309 FreeLock = 0x0001, 310 FreeAcquiredLock = 0x0002, // do not free the lock if we already held it 311 // when calling constructor 312 TearDownSession = 0x0004 313 }; 314 315 Locker(ScriptInterpreterPythonImpl *py_interpreter, 316 uint16_t on_entry = AcquireLock | InitSession, 317 uint16_t on_leave = FreeLock | TearDownSession, 318 lldb::FileSP in = nullptr, lldb::FileSP out = nullptr, 319 lldb::FileSP err = nullptr); 320 321 ~Locker() override; 322 323 private: 324 bool DoAcquireLock(); 325 326 bool DoInitSession(uint16_t on_entry_flags, lldb::FileSP in, 327 lldb::FileSP out, lldb::FileSP err); 328 329 bool DoFreeLock(); 330 331 bool DoTearDownSession(); 332 333 bool m_teardown_session; 334 ScriptInterpreterPythonImpl *m_python_interpreter; 335 PyGILState_STATE m_GILState; 336 }; 337 338 static bool BreakpointCallbackFunction(void *baton, 339 StoppointCallbackContext *context, 340 lldb::user_id_t break_id, 341 lldb::user_id_t break_loc_id); 342 static bool WatchpointCallbackFunction(void *baton, 343 StoppointCallbackContext *context, 344 lldb::user_id_t watch_id); 345 static void Initialize(); 346 347 class SynchronicityHandler { 348 private: 349 lldb::DebuggerSP m_debugger_sp; 350 ScriptedCommandSynchronicity m_synch_wanted; 351 bool m_old_asynch; 352 353 public: 354 SynchronicityHandler(lldb::DebuggerSP, ScriptedCommandSynchronicity); 355 356 ~SynchronicityHandler(); 357 }; 358 359 enum class AddLocation { Beginning, End }; 360 361 static void AddToSysPath(AddLocation location, std::string path); 362 363 bool EnterSession(uint16_t on_entry_flags, lldb::FileSP in, lldb::FileSP out, 364 lldb::FileSP err); 365 366 void LeaveSession(); 367 368 uint32_t IsExecutingPython() { 369 std::lock_guard<std::mutex> guard(m_mutex); 370 return m_lock_count > 0; 371 } 372 373 uint32_t IncrementLockCount() { 374 std::lock_guard<std::mutex> guard(m_mutex); 375 return ++m_lock_count; 376 } 377 378 uint32_t DecrementLockCount() { 379 std::lock_guard<std::mutex> guard(m_mutex); 380 if (m_lock_count > 0) 381 --m_lock_count; 382 return m_lock_count; 383 } 384 385 enum ActiveIOHandler { 386 eIOHandlerNone, 387 eIOHandlerBreakpoint, 388 eIOHandlerWatchpoint 389 }; 390 391 python::PythonModule &GetMainModule(); 392 393 python::PythonDictionary &GetSessionDictionary(); 394 395 python::PythonDictionary &GetSysModuleDictionary(); 396 397 llvm::Expected<unsigned> GetMaxPositionalArgumentsForCallable( 398 const llvm::StringRef &callable_name) override; 399 400 bool GetEmbeddedInterpreterModuleObjects(); 401 402 bool SetStdHandle(lldb::FileSP file, const char *py_name, 403 python::PythonObject &save_file, const char *mode); 404 405 python::PythonObject m_saved_stdin; 406 python::PythonObject m_saved_stdout; 407 python::PythonObject m_saved_stderr; 408 python::PythonModule m_main_module; 409 python::PythonDictionary m_session_dict; 410 python::PythonDictionary m_sys_module_dict; 411 python::PythonObject m_run_one_line_function; 412 python::PythonObject m_run_one_line_str_global; 413 std::string m_dictionary_name; 414 ActiveIOHandler m_active_io_handler; 415 bool m_session_is_active; 416 bool m_pty_secondary_is_open; 417 bool m_valid_session; 418 uint32_t m_lock_count; 419 std::mutex m_mutex; 420 PyThreadState *m_command_thread_state; 421 }; 422 423 class IOHandlerPythonInterpreter : public IOHandler { 424 public: 425 IOHandlerPythonInterpreter(Debugger &debugger, 426 ScriptInterpreterPythonImpl *python) 427 : IOHandler(debugger, IOHandler::Type::PythonInterpreter), 428 m_python(python) {} 429 430 ~IOHandlerPythonInterpreter() override = default; 431 432 llvm::StringRef GetControlSequence(char ch) override { 433 static constexpr llvm::StringLiteral control_sequence("quit()\n"); 434 if (ch == 'd') 435 return control_sequence; 436 return {}; 437 } 438 439 void Run() override { 440 if (m_python) { 441 int stdin_fd = GetInputFD(); 442 if (stdin_fd >= 0) { 443 Terminal terminal(stdin_fd); 444 TerminalState terminal_state(terminal); 445 446 if (terminal.IsATerminal()) { 447 // FIXME: error handling? 448 llvm::consumeError(terminal.SetCanonical(false)); 449 llvm::consumeError(terminal.SetEcho(true)); 450 } 451 452 ScriptInterpreterPythonImpl::Locker locker( 453 m_python, 454 ScriptInterpreterPythonImpl::Locker::AcquireLock | 455 ScriptInterpreterPythonImpl::Locker::InitSession | 456 ScriptInterpreterPythonImpl::Locker::InitGlobals, 457 ScriptInterpreterPythonImpl::Locker::FreeAcquiredLock | 458 ScriptInterpreterPythonImpl::Locker::TearDownSession); 459 460 // The following call drops into the embedded interpreter loop and 461 // stays there until the user chooses to exit from the Python 462 // interpreter. This embedded interpreter will, as any Python code that 463 // performs I/O, unlock the GIL before a system call that can hang, and 464 // lock it when the syscall has returned. 465 466 // We need to surround the call to the embedded interpreter with calls 467 // to PyGILState_Ensure and PyGILState_Release (using the Locker 468 // above). This is because Python has a global lock which must be held 469 // whenever we want to touch any Python objects. Otherwise, if the user 470 // calls Python code, the interpreter state will be off, and things 471 // could hang (it's happened before). 472 473 StreamString run_string; 474 run_string.Printf("run_python_interpreter (%s)", 475 m_python->GetDictionaryName()); 476 PyRun_SimpleString(run_string.GetData()); 477 } 478 } 479 SetIsDone(true); 480 } 481 482 void Cancel() override {} 483 484 bool Interrupt() override { return m_python->Interrupt(); } 485 486 void GotEOF() override {} 487 488 protected: 489 ScriptInterpreterPythonImpl *m_python; 490 }; 491 492 } // namespace lldb_private 493 494 #endif // LLDB_ENABLE_PYTHON 495 #endif // LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_SCRIPTINTERPRETERPYTHONIMPL_H 496