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